package hk.ces.oxfam.patch.util;

import java.util.Collection;

/**
 *
 * @author ReutyCheng
 */
public class StringUtil
{

  private StringUtil()
  {
  }

  public static final String toString(Object object, int length)
  {
    StringBuilder builder = new StringBuilder(64);
    for (int index = 0; index < length; index++)
    {
      builder.append(object + "");
      if (index + 1 < length)
      {
        builder.append(",");
      }
    }

    return builder.toString();
  }

  public static final String toString(Object[] objects)
  {
    StringBuilder builder = new StringBuilder(64);
    for (int index = 0; index < objects.length; index++)
    {
      builder.append(objects[index] + "");
      if (index + 1 < objects.length)
      {
        builder.append(",");
      }
    }

    return builder.toString();
  }

  public static final int count(String string, char character)
  {
    char[] cs = string.toCharArray();
    int count = 0;
    for (char c : cs)
    {
      if (c == character)
      {
        count++;
      }
    }

    return count;
  }

  public static final int count(String string, String fragment)
  {
    int count = 0;
    char[] stringChars = string.toCharArray();
    char[] fragmentChars = fragment.toCharArray();

    int maxIndex = stringChars.length - fragmentChars.length + 1;
    for (int startIndex = 0; startIndex < maxIndex; startIndex++)
    {
      int innerIndex = 0;
      for (; innerIndex < fragmentChars.length; innerIndex++)
      {
        char stringChar = stringChars[startIndex + innerIndex];
        char fragmentChar = fragmentChars[innerIndex];
        if (stringChar != fragmentChar)
        {
          break;
        }
      }

      if (innerIndex == fragmentChars.length)
      {
        count++;
      }
    }

    return count;
  }

  public static String ridNullValue(String value)
  {
    if (value == null || value.trim().length() == 0)
    {
      return "";
    }
    else
    {
      return value;
    }
  }

  public static final int getIndex(String string, String[] array, boolean ignoreCase)
  {
    if (ignoreCase)
    {
      for (int index = 0; index < array.length; index++)
      {
        if (array[index].equalsIgnoreCase(string))
        {
          return index;
        }
      }
    }
    else
    {
      for (int index = 0; index < array.length; index++)
      {
        if (array[index].equals(string))
        {
          return index;
        }
      }
    }

    return -1;
  }

  public static final int getIndex(String string, Collection collection, boolean ignoreCase)
  {
    if (ignoreCase)
    {
      int index = 0;
      for (Object object : collection)
      {
        if (((String) object).equalsIgnoreCase(string))
        {
          return index;
        }
      }
    }
    else
    {
      int index = 0;
      for (Object object : collection)
      {
        if (((String) object).equals(string))
        {
          return index;
        }
      }
    }

    return -1;
  }
}
